<?php


namespace app\api\controller;

use think\Cache;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\common\model\SmokeRecord;
class Health extends AuthBase
{
    public function index(){
        // 将时间戳转换为 DateTime 对象
        $user=Db::name('smoke_record')
            ->where('user_id',$this->userId)
            ->limit(1)
            ->order('id asc')
            ->find();
        $date1 = new \DateTime();
        $date1->setTimestamp($user['smoke_date']);
        $date2 = new \DateTime();
        $date2->setTimestamp(time());
        $days=get_diff_day($user['smoke_date'],time());
// 计算两个日期之间的差值
        $interval = $date1->diff($date2);
        //计算累计吸入和日均吸入
        $tar=Db::name('smoke_record')
            ->where('user_id',$this->userId)
            ->sum('tar');
        $nicotine=Db::name('smoke_record')
            ->where('user_id',$this->userId)
            ->sum('nicotine');
        $co=Db::name('smoke_record')
            ->where('user_id',$this->userId)
            ->sum('co');
        if (!$user){
            $data['year']=0;
            $data['month']=0;
            $data['day']=0;
        }else{
            $data['year']=$interval->y;
            $data['month']=$interval->m;
            $data['day']=$interval->d;
        }
        $data['total_tar']=round($tar,2);
        $data['avg_tar']=round($tar/$days,2);
        $data['total_nicotine']=round($nicotine,2);
        $data['avg_nicotine']=round($nicotine/$days,2);
        $data['total_co']=round($co,2);
        $data['avg_co']=round($co/$days,2);
        $data['is_vip']=$this->is_vip;
        return $this->show(1,'',$data);
    }
    public function statistics(){
        $type=input('get.type',1);
        if (!$type){
            $type=1;
        }
        if ($type==1){
            //获取近6日日期
            $currentDate = date('Y-m-d');
            $dates = [];
// 循环获取近 12 个日期
            for ($i = 0; $i < 7; $i++) {
                // 计算当前循环对应的日期
                $date = date('Y-m-d', strtotime("-$i days", strtotime($currentDate)));
                $dates[] = $date;
            }
            $result=[];
            foreach ($dates as $k=>$v){
                $one=explode('-',$v);
                $result[$k]['date']=end($one);
                $sum=Db::name('smoke_record')
                    ->where(['user_id'=>$this->userId])
                    ->whereDay('smoke_date',$v)
                    ->field([
                        'SUM(tar) as tar_sum',
                        'SUM(nicotine) as nicotine_sum',
                        'SUM(co) as co_sum'
                    ])
                    ->find();
                $sum['tar_sum']=round($sum['tar_sum'],2)?:0;
                $sum['nicotine_sum']=round($sum['nicotine_sum'],2)?:0;
                $sum['co_sum']=round($sum['co_sum'],2)?:0;
                $result[$k]['tar']=$sum['tar_sum'];
                $result[$k]['nicotine']=$sum['nicotine_sum'];
                $result[$k]['co']=$sum['co_sum'];
                $result[$k]['arr']=$sum;
            }
        }elseif($type==2){
            $currentDate = date('Y-m');
            $dates = [];
// 循环获取近 12 个日期
            for ($i = 0; $i < 7; $i++) {
                // 计算当前循环对应的日期
                $date = date('Y-m', strtotime("-$i month", strtotime($currentDate)));
                $dates[] = $date;
            }

            $result=[];
            foreach ($dates as $k=>$v){
                $one=explode('-',$v);
                $result[$k]['date']=end($one).'月';
                $sum=Db::name('smoke_record')
                    ->where(['user_id'=>$this->userId])
                    ->whereMonth('smoke_date',$v)
                    ->field([
                        'SUM(tar) as tar_sum',
                        'SUM(nicotine) as nicotine_sum',
                        'SUM(co) as co_sum'
                    ])
                    ->find();
                $sum['tar_sum']=round($sum['tar_sum'],2)?:0;
                $sum['nicotine_sum']=round($sum['nicotine_sum'],2)?:0;
                $sum['co_sum']=round($sum['co_sum'],2)?:0;
                $result[$k]['tar']=$sum['tar_sum'];
                $result[$k]['nicotine']=$sum['nicotine_sum'];
                $result[$k]['co']=$sum['co_sum'];
                $result[$k]['arr']=$sum;
            }
        }elseif($type==3){
            $currentDate = date('Y');
            $dates = [];
// 循环获取近 12 个日期
            for ($i = 0; $i < 7; $i++) {
                // 计算当前循环对应的日期
                $date = date('Y', strtotime("-$i year", strtotime($currentDate)));
                $dates[] = $date;
            }
            $result=[];
            foreach ($dates as $k=>$v){
                $result[$k]['date']=$v;
                $sum=Db::name('smoke_record')
                    ->where(['user_id'=>$this->userId])
                    ->whereYear('smoke_date',$v)
                    ->field([
                        'SUM(tar) as tar_sum',
                        'SUM(nicotine) as nicotine_sum',
                        'SUM(co) as co_sum'
                    ])
                    ->find();
                $sum['tar_sum']=round($sum['tar_sum'],2)?:0;
                $sum['nicotine_sum']=round($sum['nicotine_sum'],2)?:0;
                $sum['co_sum']=round($sum['co_sum'],2)?:0;
                $result[$k]['tar']=$sum['tar_sum'];
                $result[$k]['nicotine']=$sum['nicotine_sum'];
                $result[$k]['co']=$sum['co_sum'];
                $result[$k]['arr']=$sum;
            }
        }
        $data['result']=array_reverse($result);;
        $data['is_vip']=$this->is_vip;
//        $data['y_max'] = max(array_column($result, 'co'));
        return show(1,'success',$data);
//        return show(1,'success',$result);
    }
    public function log(){
        $type = input('get.type');
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $where=[];
        $where[] = [
            'user_id', '=',  $this->userId
        ];
        $book = SmokeRecord::where($where)
            ->page($page, $limit)
            ->order('smoke_date desc');
        $count = SmokeRecord::where($where);
        if ($type){
            $tar=$book->whereYear('smoke_date',$type)->sum('tar');
            $nicotine=$book->whereYear('smoke_date',$type)->sum('nicotine');
            $co=$book->whereYear('smoke_date',$type)->sum('co');
            $book=$book->whereYear('smoke_date',$type)
                ->column('id,smoke_date,tar,nicotine,co');
            $count=$count->whereYear('smoke_date',$type)
                ->count();
        }else{
            $tar=$book->sum('tar');
            $nicotine=$book->sum('nicotine');
            $co=$book->sum('co');
            $book = $book->column('id,smoke_date,tar,nicotine,co');
            $count = $count->count();
        }
        foreach ($book as $k => $v) {
            $book[$k]['smoke_date']=date("Y/m/d H:i",$v['smoke_date']);
        }

        //处理头部数据
        $top['tar']=round($tar,2);
        $top['nicotine']=round($nicotine,2);
        $top['co']=round($co,2);
        $count = intval(ceil($count / $limit));
        $data['list'] = $book;
        $data['top'] = $top;
        $data['count'] = $count;
        return $this->show(1, '', $data);
    }
    public function log_export(){
        $user=Db::name('user')
            ->where('id',$this->userId)
            ->find();
        $email=input('get.email');
        $type=input('get.type');
        if ($type){
            $res=Db::name('smoke_record')
                ->where('user_id',$this->userId)
                ->whereYear('smoke_date',$type)
                ->order('smoke_date desc')
                ->column('smoke_date,tar,nicotine,co,num,create_time');
        }else{
            $res=Db::name('smoke_record')
                ->where('user_id',$this->userId)
                ->order('smoke_date desc')
                ->column('smoke_date,tar,nicotine,co,num,create_time');
        }
        $spreadsheet = new Spreadsheet();
        // 获取当前活动的工作表（默认第一个工作表）
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $sheet->setCellValue('A1', '日期');
        $sheet->setCellValue('B1', '摄入尼古丁量');
        $sheet->setCellValue('C1', '摄入一氧化碳量');
        $sheet->setCellValue('D1', '摄入焦油量');
        $sheet->setCellValue('E1', '吸入棵数');
        $sheet->setCellValue('F1', '记录时间');


        // 模拟一些数据，实际应用中可从数据库等获取
        $data_two=[];
        foreach ($res as $k=>$v) {
            $data_two[$k][]=date("Y-m-d H:i",$v['smoke_date']);
            $data_two[$k][]=$v['nicotine'];
            $data_two[$k][]=$v['co'];
            $data_two[$k][]=$v['tar'];
            $data_two[$k][]=$v['num'];
            $data_two[$k][]=date("Y-m-d H:i",$v['create_time']);
        };
        // 填充数据行
        $row = 2;
        foreach ($data_two as $rowData) {
            $col = 'A';
            foreach ($rowData as $value) {
                $sheet->setCellValue($col. $row, $value);
                $col++;
            }
            $row++;
        }

        // 创建一个临时文件用于保存Excel内容，这里以xlsx格式为例
        $fileName = 'export/'.$user['invite_code'].'.xlsx';
        $writer = new Xlsx($spreadsheet);
        $writer->save($fileName);
        //存储完之后,发送邮件
        $subject=$user['nickname']."您的数据导出已完成";
        $res=sendMailFile($email,$user['nickname'],$fileName,$subject);
        if ($res){
            return $this->show(1,'导出成功请查看邮箱');
        }
        return show(0,'导出失败');
    }
}
